<template>
  <div>
    <div class="chart_box" v-loading="isLoading">
      <div ref="myChart" class="chart_wrapper"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoadQueryChart',
  props: {
    // 表格列表
    tableColumns: Array,
    // 负荷查询：当前年份
    currentYear: Date,
    // 负荷查询：所选班组
    workgroupId: String,
    // 负荷查询：所选工作中心
    workcenterId: String
  },
  data() {
    return {
      isLoading: false, // 表格是否加载
      chartData: {}, // 图表数据
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      this.getDetailData()
    },
    // 初始化方法
    getDetailData() {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/workshopload',
        data: {},
        noCommit: true
      }
      if (this.currentYear) {
        const date = new Date(this.currentYear)
        postData.data.beginPracticalStartDate = this.moment(date).startOf('year').format('YYYY-MM-DD 00:00:00')
        postData.data.endPracticalStartDate = this.moment(date).endOf('year').format('YYYY-MM-DD 23:59:59')
      }
      if (this.workgroupId) {
        postData.data.workgroupId = this.workgroupId
      }
      if (this.workcenterId) {
        postData.data.workcenterId = this.workcenterId
      }
      this.$store.dispatch('saveData', postData).then(res => {
        this.chartData = res.data || []
        this.getEchartsData()
        this.renderEcharts()
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 图表所需数据
    getEchartsData() {
      this.month = [] // x轴
      this.plannedTime = [] // 定额工时
      this.expendTime = [] // 实际工时
      this.chartData.forEach(item => {
        this.month.push(item.month)
        this.plannedTime.push(item.estimateEffort || 0)
        this.expendTime.push(item.expendTime || 0)
      })
    },
    /**
     * 渲染图表
     */
    renderEcharts() {
      let myChart = this.$echarts.init(this.$refs.myChart)
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          padding: 10,
          textStyle: {
            fontSize: 12,
            lineHeight: 40
          },
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
          formatter: (params) => {
            const currentData = this.chartData.find((item) => item.month === params[0].axisValue)
            const workstageList = currentData.workstageList || []
            const title = `<p>${params[0].axisValue}：定额${currentData.estimateEffort} | 实际${currentData.expendTime}</p>`
            return title + this.getTooltipData(workstageList)
          }
        },
        // 画板边距
        grid: {
          left: '60',
          right: '60',
        },
        legend: {
          data: [
            {name: '定额工时'},
            {name: '实际工时'},
          ],
          itemWidth: 24,
          itemHeight: 10,
        },
        xAxis: [
          {
            type: 'category',
            data: this.month,
            // x轴轴线颜色和宽度
            axisLine: {
              lineStyle: {
                color: '#dcdfe6',
                width: 2
              }
            },
            // x轴字体颜色
            axisLabel: {
              show: true,
              textStyle: {
                color: 'rgba(0, 0, 0, 0.65)'
              }
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '小时',
            // Y轴虚线
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)',
                width: 1,
                type: 'dashed'
              }
            },
            // y轴轴线
            axisLine: {'show': false},
            //y轴刻度线
            axisTick: {'show': false},
          }
        ],
        // 数据
        series: [
          {
            name: '定额工时',
            type: 'bar',
            data: this.plannedTime,
            barMaxWidth: 160,
            barMinHeight: 0,
            itemStyle: {
              normal: {
                color: '#1890ff',
                opacity: 0.85
              }
            }
          },
          {
            name: '实际工时',
            type: 'bar',
            data: this.expendTime,
            barMaxWidth: 160,
            barMinHeight: 0,
            itemStyle: {
              normal: {
                color: '#37cccc',
                opacity: 0.85
              }
            }
          },
        ]
      })
    },
    // 整理描述图表tooltip
    getTooltipData(list) {
      if (Array.isArray(list)) {
        // 计算tooltip最多只能展示30个工序,超出30个的工序统计集合成"其他"
        const afterList = list.slice(29)
        const estimateEffort = afterList.reduce((a, b) => a + b.estimateEffort, 0)
        const expendTime = afterList.reduce((a, b) => a + b.expendTime, 0)
        let rootList = list.slice(0, 29)
        if (afterList.length > 0) {
          rootList.push({workstageName: '其他', estimateEffort: estimateEffort, expendTime: expendTime})
        }
        return this.joinTooltip(rootList)
      }
    },
    /**
     * 拼接toolitip的展示内容
     * @param rootList 工序展示列表
     * @returns {string}
     */
    joinTooltip(rootList) {
      // 拼接出tooltip的展示内容
      let str = ''
      rootList.forEach((item, index) => {
        if ((index + 1) % 2 === 0) {
          const leftStr = `<span style="display: inline-block; width: 200px;">${rootList[index - 1].workstageName}：定额${rootList[index - 1].estimateEffort} | 实际${rootList[index - 1].expendTime}</span>`
          const rightStr = `<span style="display: inline-block;">${item.workstageName}：定额${item.estimateEffort} | 实际${item.expendTime}</span>`
          str += `<p>${leftStr}${rightStr}</p>`
        }
      })
      if (rootList.length % 2 !== 0) {
        const item = rootList[rootList.length - 1]
        const leftStr = `<span style="display: inline-block;">${item.workstageName}：定额${item.estimateEffort} | 实际${item.expendTime}</span>`
        str += `<p>${leftStr}</p>`
      }
      return str
    }
  }
}
</script>

<style scoped>

</style>
